using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Linq;

namespace FileRename
{
    public partial class frmRename : Form
    {
        public frmRename()
        {
            InitializeComponent();
        }

        private void btnRename_Click(object sender, EventArgs e)
        {
            try
            {
                MP3Manipulator.Rename(txtFolder.Text, txtMatchNamePattern.Text, txtReplacementPattern.Text);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(
                    string.Format("Error invoking rename. {0}{0}{1}", Environment.NewLine, ex),
                    "Error renaming file",
                    System.Windows.Forms.MessageBoxButtons.OK,
                    System.Windows.Forms.MessageBoxIcon.Error);
            }
        }

        private void btnMP3Analyze_Click(object sender, EventArgs e)
        {
            try
            {
                lvMatches.Items.Clear();

                IEnumerable<IAnalyzer> items = MP3Manipulator.AnalyzeForRussification(
                    txtFolder.Text, 
                    txtMP3IDMatchPattern.Text, 
                    checkIncludeFolders.Checked,
                    chkTransliterate.Checked,
                    (Encoding)cmbSourceEncoding.SelectedItem,
                    (Encoding)cmbDestinationEncoding.SelectedItem);

                foreach (IAnalyzer item in items)
                {
                    AddItemToAnalysisResultList(item);
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(
                    string.Format("Error analyzing mp3 headers. {0}{0}{1}", Environment.NewLine, ex),
                    "MP3 Analysis Error",
                    System.Windows.Forms.MessageBoxButtons.OK,
                    System.Windows.Forms.MessageBoxIcon.Error);
            }
        }

        private void AddItemToAnalysisResultList(IAnalyzer item)
        {
            ListViewItem lvi = new ListViewItem(new string[]
                {
                    Path.GetFileName(item.FilenamePath),
                    item.FilenameProposed,
                    item.SongNameCurrent,
                    item.SongNameProposed,
                    item.AlbumCurrent, 
                    item.AlbumProposed,
                    item.ArtistCurrent, 
                    item.ArtistProposed
                });

            lvi.Tag = item;

            lvi.Checked = true;

            lvMatches.Items.Add(lvi);
        }

        private void btnRussify_Click(object sender, EventArgs e)
        {
            var items = new List<IAnalyzer>();
            foreach (ListViewItem item in lvMatches.Items)
            {
                if (item.Tag is IAnalyzer && item.Checked)
                {
                    items.Add(item.Tag as IAnalyzer);
                }
            }

            var folders = items.OfType<DirectoryTransliterateAnalysis>().Cast<IAnalyzer>().Concat(items.OfType<DirectoryRussifyAnalysis>()).OrderByDescending(f => f.FilenamePath.Length);
            var files = items.OfType<MP3TransliterateAnalysis>().Cast<IAnalyzer>().Concat(items.OfType<MP3RussifyAnalysis>());

            var combinedActions = files.Concat(folders);

            foreach (IAnalyzer action in combinedActions)
            {
                action.ApplyAnalysis();
            }
        }

        private void txtIDTagToFilenameRegexMask_TextChanged(object sender, EventArgs e)
        {
            CalculateTagToFileRenamePreview();
        }

        private void CalculateTagToFileRenamePreview()
        {
            try
            {
                lvTagToFilename.Items.Clear();

                IEnumerable<RenameFileByTag> items = MP3Manipulator.AnalyzeForRenameByTag(txtFolder.Text, 
                    txtIDTagToFilenameSourceRegexMask.Text, 
                    txtIDTagToFilenameDestinationMask.Text);

                foreach (RenameFileByTag item in items)
                {
                    AddItemToTagToFilenamePreviewList(item);
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(
                    string.Format("Error analyzing mp3 headers. {0}{0}{1}", Environment.NewLine, ex),
                    "MP3 Analysis Error",
                    System.Windows.Forms.MessageBoxButtons.OK,
                    System.Windows.Forms.MessageBoxIcon.Error);
            }

        }

        private void AddItemToTagToFilenamePreviewList(RenameFileByTag item)
        {
            ListViewItem lvi = new ListViewItem(new string[]
                {
                    Path.GetFileName(item.CurrentFilename),
                    item.Matched.ToString(),
                    item.ProposedFilename
                });

            lvi.Tag = item;

            lvi.Checked = true;

            lvTagToFilename.Items.Add(lvi);
        }

        private void btnTagToFileRename_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (ListViewItem lvi in lvTagToFilename.Items)
                {
                    if (lvi.Checked)
                    {
                        RenameFileByTag item = lvi.Tag as RenameFileByTag;

                        if (item != null)
                        {
                            item.ApplyRename();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(
                    string.Format("Error renaming files from headers. {0}{0}{1}", Environment.NewLine, ex),
                    "MP3 File from header rename Error",
                    System.Windows.Forms.MessageBoxButtons.OK,
                    System.Windows.Forms.MessageBoxIcon.Error);
            }
        }

        private void frmRename_Load(object sender, EventArgs e)
        {
            cmbSourceEncoding.BeginUpdate();
            cmbSourceEncoding.Items.AddRange(Encoding.GetEncodings().Select(ei => ei.GetEncoding()).ToArray());
            cmbSourceEncoding.EndUpdate();

            cmbDestinationEncoding.BeginUpdate();
            cmbDestinationEncoding.Items.AddRange(Encoding.GetEncodings().Select(ei => ei.GetEncoding()).ToArray());
            cmbDestinationEncoding.EndUpdate();

            cmbSourceEncoding.SelectedItem = Encoding.GetEncoding("windows-1252");
            cmbDestinationEncoding.SelectedItem = Encoding.GetEncoding("windows-1251");
        }
    }
}